import { AesEncryption } from './aesEncryption.js';
console.log('test')
console.log('test2');
const defaultConfig = {
  prefixKey: '',
  hasEncrypt: true,
  key: '_11111000001111@',
  iv: '@11111000001111_',
};

const encryption = new AesEncryption({
  key: defaultConfig.key,
  iv: defaultConfig.iv,
});

class WebStorage {
  constructor(storage, {
    prefixKey = '',
    hasEncrypt = true,
  }) {
    this.storage = storage;
    this.prefixKey = prefixKey;
    this.hasEncrypt = hasEncrypt;
  }
  updateConfig({
    prefixKey = '',
    hasEncrypt = true,
  }) {
    this.prefixKey = prefixKey;
    this.hasEncrypt = hasEncrypt;
  }
  /**
   * 获取缓存键值
   * @param {*} key 
   * @returns 
   */
  getKey(key) {
    return `${this.prefixKey}${key}`.toUpperCase();
  }
  /**
   * 获取缓存值
   * @param {*} key 
   * @param {*} def 默认值
   * @returns 
   */
  get(key, def = null) {
    const val = this.storage.getItem(this.getKey(key));
    if (!val) {
      return def;
    }
    const decVal = this.hasEncrypt?encryption.decryptByAES(val) : val;
    const data = JSON.parse(decVal);
    const { value, time, expire } = data;
    if (expire !== 0 && (time +  expire * 1000) < Date.now()) {
      this.remove(key);
      return def;
    }
    return value;
  }
  /**
   * 设置缓存值
   * @param {*} key 
   * @param {*} value 
   * @param {*} expire 过期的秒数(0为永不过期)
   */
  set(key, value, expire = 0) {
    const stringData = JSON.stringify({
      value,
      time: Date.now(),
      expire,
    });
    const stringifyValue = this.hasEncrypt?encryption.encryptByAES(stringData):stringData;
    this.storage.setItem(this.getKey(key), stringifyValue);
  }
  /**
   * 移除缓存值
   * @param {*} key 
   */
  remove(key) {
    this.storage.removeItem(this.getKey(key));
  }
  /**
   * 清空缓存
   */
  clear() {
    this.storage.clear();
  }
}

export const LocalStorageCache = new WebStorage(window.localStorage, {});

export const SessionStorageCache = new WebStorage(window.sessionStorage, {});

export function cacheConfig ({
  prefixKey = defaultConfig.prefixKey,
  hasEncrypt = defaultConfig.hasEncrypt,
  key = defaultConfig.key,
  iv = defaultConfig.iv,
}) {
  encryption.updateConfig({
    key,
    iv,
  });
  LocalStorageCache.updateConfig({
    prefixKey,
    hasEncrypt,
  });
  SessionStorageCache.updateConfig({
    prefixKey,
    hasEncrypt,
  });
}